<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24" class="mb-[12px]">
        <el-card style="min-width: 480px;margin-bottom: 18px;">
          <template #header>
            <div class="card-header">
              <span>问题发起</span>
            </div>
          </template>

          <el-form
            ref="problemFormRef"
            :model="formData"
            :rules="rules"
            label-width="120px"
          >
            <div class="form-flex">
              <el-form-item label="问题标题" prop="title" class="form-item">
                <el-input v-model="formData.title" />
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="问题来源" prop="source" class="form-item">
                <el-select v-model="formData.source">
                  <el-option label="内部问题" value="1" />
                  <el-option label="外部问题" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="问题等级" prop="level" class="form-item">
                <el-select v-model="formData.level">
                  <el-option label="致命" value="1" />
                  <el-option label="严重" value="2" />
                  <el-option label="一般" value="3" />
                  <el-option label="提示" value="4" />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="问题描述" prop="description">
                <div style="border: 1px solid #ccc; margin-top: 10px;">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :mode="mode"
                  />
                  <Editor
                    style="height: 200px; overflow-y: hidden;width: 1000px;"
                    v-model="formData.description" 
                    :mode="mode"
                    :defaultConfig="editorConfig"
                    @onCreated="handleCreated"
                    @onChange="handleChange"
                  />
                </div>
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="期望解决时间" prop="expectTime" class="form-item">
                <el-date-picker
                  v-model="formData.expectTime"
                  type="datetime"
                />
              </el-form-item>
              <el-form-item label="责任人" prop="assigner" class="form-item">
                <el-select v-model="formData.assigner" filterable>
                  <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"/>
                </el-select>
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="提出人" prop="creator" class="form-item">
                <el-select v-model="formData.creator" :disabled="true">
                  <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"/>
                </el-select>
              </el-form-item>
              <el-form-item label="提出时间" prop="createTime" class="form-item">
                <el-date-picker
                  v-model="formData.createTime"
                  type="datetime"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="附件" prop="attachments" class="form-item">
                <el-upload
                  v-model:file-list="fileList"
                  class="upload-demo"
                  action="/api/bus/upload/uploadFiles"
                  multiple
                  :on-remove="handleRemove"
                  :limit="3"
                  :on-success="handleFileSuccess"
                  :before-upload="beforeFileUpload"
                  :on-preview="handleFilePreview"
                >
                  <el-button type="primary">上传附件</el-button>

                </el-upload>
              </el-form-item>
            </div>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">提 交</el-button>
              <el-button type="primary" @click="handleSave">暂 存</el-button>
            </div>
          </template>
        </el-card>

        <!-- 流程设置弹窗 -->
        <el-dialog
          v-model="workNodesVisible"
          title="流程配置"
          width="550px"
          @close="handleCloseDialog"
        >
          <el-table
            ref="workNodesRef"
            v-loading="loading"
            :data="workNodeList"
            highlight-current-row
            border
          >
            <el-table-column label="节点名称" prop="nodeName" min-width="120" />
            <el-table-column label="处理人" prop="userId" min-width="150" >
              <template #default="{ row }">
                <el-select placeholder="请选择处理人" v-model="row.userId" filterable>
                  <el-option
                  value="0"
                  label="请选择"/>
                  <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" prop="inuse" width="150" >
              <template #default="{ row }">
                <el-radio-group v-model="row.inuse">
                  <el-radio value="1">是</el-radio>
                  <el-radio value="0">否</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
          </el-table>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="handleSubmit">确 定</el-button>
              <el-button @click="handleCloseDialog">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ProblemApply",
  inheritAttrs: false,
});

import ProjectAPI, { ProjectProblemData } from "@/api/project";
import UserAPI from "@/api/user";
import router from "@/router";
import { useTagsViewStore, useSettingsStore } from "@/store";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css

const route = useRoute();
const tagsViewStore = useTagsViewStore();
const settingsStore = useSettingsStore();
const problemFormRef = ref(ElForm);

// 人员选择框
const userList = ref([]);

// 项目表单
const formData = reactive<ProjectProblemData>({
  processId: 0,
  workNodes: '',
});
const rules = reactive({
  title: [{ required: true, message: "请输入问题标题", trigger: "blur" },{ min: 1, max: 50, message: '输入长度在 1 到 50 个字符', trigger: 'blur' }],
  source: [{ required: true, message: "请选择问题来源", trigger: "blur" }],
  level: [{ required: true, message: "请选择问题等级", trigger: "blur" }],
  description: [{ required: true, message: "请输入问题描述", trigger: "blur" }],
  expectTime: [{ required: true, message: "请输入期望解决时间", trigger: "blur" }],
  assigner: [{ required: true, message: "请选择责任人", trigger: "blur" }],
});

// 富文本
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = {MENU_CONF: {}}
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: '',	
  },
  server: "/api/upload/uploadFile",  // 服务端图片上传接口
  fieldName: 'file',  // 服务端图片上传接口参数名
  // 后端返回的图片地址不是完整的，可以在这里补全
  customInsert: (res, insertFn) => {
    const imageUrl = res.data;
    insertFn(imageUrl);
  },
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor
}
// 监听文本框
const handleChange = (editor) => {
  formData.description = editor.getHtml();
}

const fileList = ref<UploadUserFile[]>([])
const handleFileSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  formData.attachments = response.data
}
const beforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }
  return true
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  // console.log(file, uploadFiles)
}

// 实例节点设置相关
const workNodesVisible = ref(false);
const workNodesRef = ref(ElForm);
const workNodeList = ref([]);

const loading = ref(false);
/** 提交问题表单 */
const submitForm = () => {
  problemFormRef.value.validate((valid: any) => {
    if (valid) {
      if (route.query.workId){ // 流程已启动，直接提交
        handleSubmit();
      }
      else{ // 流程未启动，启动实例节点配置
        workNodesVisible.value = true;
        if (workNodeList.value.length == 2){
          workNodeList.value[0].userId = formData.assigner;
          workNodeList.value[1].userId = formData.creator;
        }
      }
    }
  });
}
const handleSubmit = () => {
    // 处理附件
    let files = [];
    for(let i = 0; i < fileList.value.length; i++){
      if (fileList.value[i].response){
        files.push(fileList.value[i].response.data[0])
      }
      else{
        let fileJson = {};
        fileJson.name = fileList.value[i].name;
        fileJson.url = fileList.value[i].url;
        files.push(fileJson);
      }
    }
    formData.attachments = JSON.stringify(files);
    // 处理节点配置
    if (!route.query.workId){
      let nodes = [];
      let counter = 0;
      for(let i in workNodeList.value ){
        let workNode = workNodeList.value[i];
        let tmp = [workNode.nodeId, workNode.userId, workNode.inuse];
        nodes.push(tmp.join(","));
        if (workNode.inuse == "0"){
          counter++;
        }
      }
      // 不允许全部审批节点禁用
      if (counter == workNodeList.value.length){
        ElMessage.warning("不允许禁用所有节点");
        return;
      }
      formData.workNodes = nodes.join(";");
    }
    loading.value = true;
    ProjectAPI.problemApply(formData)
        .then((data) => {
          ElMessage.success(data.msg);
          ElMessage.success(data.data);
          // router.push({ path: '/projectList/details' });
          if (settingsStore.tagsView){
            tagsViewStore.closeCurrentView();
          }
          router.go(-1)
        })
        .finally(() => (loading.value = false));
}

/** 保存问题表单 */
const handleSave = () => {
  problemFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      // 处理附件
      let files = [];
      for(let i = 0; i < fileList.value.length; i++){
        if (fileList.value[i].response){
          files.push(fileList.value[i].response.data[0])
        }
        else{
          let fileJson = {};
          fileJson.name = fileList.value[i].name;
          fileJson.url = fileList.value[i].url;
          files.push(fileJson);
        }
      }
      formData.attachments = JSON.stringify(files);
      ProjectAPI.problemSave(formData)
          .then(({data}) => {
            formData.id = data; // id回写
            ElMessage.success("暂存成功");
          })
          .finally(() => (loading.value = false));
    }
  });
}

function handleCloseDialog(){
  workNodesVisible.value = false;
}

function handleFilePreview(file) {
  const fileUrl = file.url
  const a = document.createElement('a')
  a.href = fileUrl
  a.download = file.name
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

onMounted(() => {
  formData.projectId = route.query.projectId;
  if (route.query.id){
    ProjectAPI.getProblemById(route.query.id).then(({data}) => {
      if (data){
        formData.id = data.id;
        formData.title = data.title;
        formData.source = data.source.toString();
        formData.level = data.level.toString();
        formData.description = data.description;
        formData.expectTime = data.expectTime;
        formData.status = data.status;
        formData.creator = data.creator;
        formData.createTime = data.createTime;
        formData.assigner = data.assigner;
        formData.attachments = data.attachments;
        if (formData.attachments){
          let files = JSON.parse(formData.attachments);
          for(let i = 0; i < files.length; i++){
            fileList.value.push({name: files[i]["name"], url: files[i]["url"]});
          }
        }
      }
    })
  }
  else if (route.query.workId){
    ProjectAPI.getProblemByWorkId(route.query.workId).then(({data}) => {
      if (data){
        formData.id = data.id;
        formData.title = data.title;
        formData.source = data.source.toString();
        formData.level = data.level.toString();
        formData.description = data.description;
        formData.expectTime = data.expectTime;
        formData.status = data.status;
        formData.creator = data.creator;
        formData.createTime = data.createTime;
        formData.assigner = data.assigner;
        formData.attachments = data.attachments;
        if (formData.attachments){
          let files = JSON.parse(formData.attachments);
          for(let i = 0; i < files.length; i++){
            fileList.value.push({name: files[i]["name"], url: files[i]["url"]});
          }
        }
      }
    })
  }

  if (route.query.processId) {
    formData.processId = route.query.processId;
  }

  ProjectAPI.getProblemFlowNodes().then(({data}) => {
    if (data){
      for (let i in data){
        workNodeList.value.push({nodeId: data[i].nodeId, userId: "0", inuse: "1", nodeName: data[i].nodeName })
      }
    }
  })

  // 获取用户列表
  UserAPI.getUserList()
    .then(({data}) => {
      userList.value = data;
      formData.creator = parseInt(sessionStorage.getItem('userId'));
  })
});
</script>

<style type="text/css">
  .form-flex {
    display: flex;
    gap: 10px; /* 间距 */
    margin-bottom: 18px;
  }
  .form-item {
    flex: 1; /* 使所有表单项平均分配空间 */
    margin: 0; /* 移除默认的 margin */
  }
</style>

